package com.hh.service.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.hh.common.constants.Constants;
import com.hh.common.exception.HhException;
import com.hh.common.utils.RedisUtil;
import com.hh.common.vo.ValidateCode;
import com.hh.service.service.ValidateCodeService;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * ValidateCodeService 实现类
 * +----------------------------------------------------------------------
 * | hh [ hh赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2022 https://www.hh.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed hh并不是自由软件，未经许可不能去掉hh相关版权
 * +----------------------------------------------------------------------
 * | Author: hh Team <admin@hh.com>
 * +----------------------------------------------------------------------
 */
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Resource
    private RedisUtil redisAdminUtil;

    /**
     * 获取验证码信息
     */
    @Override
    public ValidateCode get() {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
        captcha.setLen(2);
        String key = UUID.randomUUID().toString();
        String value = captcha.text().toLowerCase();
        String redisKey = this.getRedisKey(key);
        this.redisAdminUtil.set(redisKey, value, 5L, TimeUnit.MINUTES);   //5分钟过期
        String base64Str = captcha.toBase64();
        return new ValidateCode(key, base64Str);
    }

    /**
     * 获取redis key
     * @param md5Key value的md5加密值
     */
    public String getRedisKey(String md5Key) {
        return Constants.VALIDATE_REDIS_KEY_PREFIX + md5Key;
    }

    /**
     * 验证
     */
    @Override
    public Boolean check(String key, String code) {
        if (!redisAdminUtil.exists(getRedisKey(key))) {
            throw new HhException("验证码错误");
        }
        Object redisValue = redisAdminUtil.get(getRedisKey(key));
        if (ObjectUtil.isNull(redisValue)) {
            return false;
        }
        return redisValue.equals(code.toLowerCase());
    }
}

